#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#define EDIT_MAX_BUFF_LEN 1024
#define EDIT_SAVE_DEFAULT_NAME "undef"

int edit_open_file(char *path)
{
    int fd = open(path, O_RDWR);
    if (fd < 0)
    {
        dprintf("editor: open file %s error\n", path);
        return -1;
    }
    dprintf("editor: open %s file ok\n", path);

    return fd;
}

int edit_open_new(char *path)
{
    int fd = open(path, O_RDWR | O_CREATE);
    if (fd < 0)
    {
        dprintf("editor: create new %s file error\n", path);
        return -1;
    }
    lseek(fd, 0, SEEK_SET);

#if EDIT_CORE_DEBUG == 1
    dprintf("editor: create new %s file ok\n", path);
#endif

    return fd;
}

int edit_save_default(char *buff, uint64_t len)
{
    char *name = EDIT_SAVE_DEFAULT_NAME;
    char path[MAX_PATH_LEN];

    memset(path, 0, MAX_PATH_LEN);

    //get current work director to make absolution path
    if (getcwd(path, MAX_PATH_LEN) == NULL)
    {
        dprintf("[editor] save error\n");
        return -1;
    }
    strcat(path, name);

#if EDIT_CORE_DEBUG == 1
    dprintf("save default: save path: name %s path %s\n", name, path);
#endif

    edit_save(path, buff, len);

    edit_save(path, buff, len);

    //edit_save(path,buff,len);
    return 0;
}

//save file to disk
int edit_save(char *path, char *buff, uint64_t len)
{
    int fd = -1;

    if (!access(path, F_OK)) //CHECK FILE STATUS
    {
        fd = edit_open_file(path);
    }
    else
    {
        fd = edit_open_new(path);
    }
    if (fd < 0)
    {
        dprintf("[editor] save error\n");
        return -1;
    }
    write(fd, buff, len);
    close(fd);
}

int edit_load_to_screen(char *path)
{
    if (!access(path, F_OK)) //check file exists
    {
        int fd = edit_open_file(path);
        if (fd < 0)
        {
            dprintf("[editor] open file %s error when try load\n", path);
            return -1;
        }
        char buff[EDIT_MAX_BUFF_LEN];
        uint32_t reads = 0;
        do //loop load file
        {
            reads = edit_load_buff(fd, buff, EDIT_MAX_BUFF_LEN);
            if (reads > 0)
            {
                edit_ctrl_outstr(buff); //output to screen window
            }
        } while (reads > 0);
        dprintf("load file success\n");
        return 0;
    }
    else
    {
        dprintf("[editor] load file %s no exist\n", path);
        return -1;
    }
}

//read file data to buffer
int edit_load_buff(int fd, char *buff, int len)
{
    int bytes = read(fd, buff, len);
    if (bytes <= 0)
    {
        dprintf("[editor] file read end\n");
        return 0;
    }
    return bytes;
}